#include "BasicOLED.h"
#include <wiringPi.h>
void CBasicLED::sendLED(uchar data, int bData)
{
  	bData == 0 ? \
	digitalWrite(LED_DC,  LOW) : digitalWrite(LED_DC,  HIGH);
	pSpi->write(data);
	
}

void CBasicLED::initLED()
{
	sendLED(0xAE, 0);
	sendLED(0xC8, 0); 
	sendLED(0xA1, 0); 
	sendLED(0x81, 0);
	sendLED(0xDF, 0);
}

void CBasicLED::reinitLED() 							
{
	digitalWrite(LED_RES, HIGH);  // RES
	sendLED(0xAF, 0);	
}

void CBasicLED::setLedAddr(unsigned char nPage, unsigned char nColumn)		
{
	delay(1);
    sendLED(0x40, 0);							// setAddrAt(0,0)
	sendLED(nPage & 0x07 | 0xB0, 0); 			// page[0xB0--0xB7]
	sendLED((nColumn>>4) | 0x10, 0);			// High 4 bit
	sendLED(nColumn & 0x0F, 0);					// Low 4 bit
	delay(1);
}

void CBasicLED::addAByte(uchar* buf, uchar x, uchar y)
{
	if(x > 7 || y > 127)
		return;
	int nEndPage,  nEndColumn;
	
	nEndPage 	= x < 6 ? x + 2 : 8; 
	nEndColumn	= y < 120?y + 8	:128;
	
	for(int i=x; i<nEndPage; i++)
	{
		for(int j=y; j<nEndColumn; j++)
		{
			m_nMem[i][j] = buf[8*(i-x) + j-y];
		}
	}
}

void CBasicLED::setMemery(uchar* buf, int nLength, uchar x, uchar y)
{
	if(nLength == 0 || nLength % 16 != 0)
		return;
	if(x > 7 || y > 127)					// 不允许自动换行
		return;
	
	int nByteCnt = nLength / 16;
	for(int i=0; i<nByteCnt; i++)
	{
		addAByte(buf+i*16, x, y+i*8);
	}
}

void CBasicLED::clearMemery(uchar data)
{

	for(uchar i=0; i<8; i++)
		for(uchar j=0; j<128; j++)
			m_nMem[i][j] = data;
}

void CBasicLED::sendScreen()
{   
	reinitLED();
	for(uchar i=0; i<8; i++)			// page
	{
		setLedAddr(i,0);
		for(uchar j=0; j<128; j++)		// column
		{
			sendLED(m_nMem[i][j]);			
		}
	}
}


void CBasicLED::setDigital(char* str, float data)
{
	int nData = (int)(data*10000);
	int n = nData;
	int i = 0;
	
	if(nData < 0) 	n *= -1;			// 四舍五入运算
	for(i=10 ; i<=100; i*=10)
	{
		if(n%i >= i/2)
			n  += i;
		n -= n%i;
	}
	// if(nData < 0) 	n *= -1;
	
	n /= 100;							// 拆解为显示字符
	for(i=0; i<5; i++)
	{
		str[i] = (char)(n % 10);
		n  /= 10;
	}
	
	for(i=4; i>2; i--)					// 左边第一个非0位
	{
		if(str[i] == 0)
			str[i] = 10;				// ' '
		else break;
	}
	
	if(i < 4)		i++;
	if(nData < 0)	str[i] = 11;		// '-' 
}

void CBasicLED::Enable(bool bChose)
{
	LED_CS = bChose ? HIGH : LOW;
}

CBasicLED::CBasicLED(CBasicSpi *pspi)
{
	this->pSpi = pspi;
	this->LED_DC = 2; //  pSpi->misoPin();
	LED_RES = 0;
	LED_CS  = 1;
}

void CBasicLED::begin()
{
	// [0, 7] : [SPI_18MHZ, SPI_140_625KHZ ]
	pSpi->begin(); // SPI_281_250KHZ SPI_140_625KHZ

	pinMode(LED_DC, OUTPUT);
	pinMode(LED_RES, OUTPUT);
	initLED();

    clearMemery(0);

}

void CBasicLED::begin(uchar DC, uchar CS, uchar RES)
{
	LED_DC  = DC;
	LED_CS  = CS;
	LED_RES = RES;

	begin();
}
